package com.caseProcess.interceptor;

import com.caseProcess.entity.Operation;
import com.caseProcess.entity.User;
import com.caseProcess.entity.VUserInfo;
import com.caseProcess.service.OperationService;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author kittlen
 * 用于基本拦截,账号信息校验与跨域信息添加
 * @version 1.0
 * @date 2020/8/2 16:23
 */
public class MyInterceptor implements HandlerInterceptor {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Resource
    private OperationService operationService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Object user=httpServletRequest.getSession().getAttribute("police");
        if(user==null){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.html");
            return false;
        }
        String policeId = httpServletRequest.getHeader("policeId");
        VUserInfo vUserInfo= (VUserInfo) user;
        if(policeId==null||!vUserInfo.getPoliceId().equals(policeId)){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.html");
            return false;
        }
        //添加操作日志
        String operationUri=httpServletRequest.getRequestURI();
        if(isNoExclude(operationUri)) {
            //拦截器会进行两次调用,所以session中添加一个参数用于防止二次提交
            Object isOperation= httpServletRequest.getSession().getAttribute("isOperation");
            if(isOperation==null){
                Map<String, String[]> map= httpServletRequest.getParameterMap();
                String parameters=new Gson().toJson(map);
                Operation operation = new Operation();
                operation.setOperationUri(operationUri);
                operation.setOperationParameters(parameters);
                User operationuser = new User();
                operationuser.setPoliceId(vUserInfo.getPoliceId());
                operation.setUser(operationuser);
                operationService.insert(operation);
                httpServletRequest.getSession().setAttribute("isOperation","1");
            }
        }
        httpServletResponse.setContentType("textml;charset=UTF-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "0");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("XDomainRequestAllowed","1");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        if(e!=null){
            logger.error("Controller:"+o.toString()+" Error:"+e.getMessage());
        }
        httpServletRequest.getSession().setAttribute("isOperation",null);
    }

    /**
     * 需要排除的关键字
     * @param uri
     * @return
     */
    public boolean isNoExclude(String uri){
        //get|select查询方法
        //quit退出方法
        //error异常页面
        //fileDown文件下载
        //fileUpload文件上传
        if(uri.indexOf("get")==-1&&uri.indexOf("select")==-1&&uri.indexOf("quit")==-1&&uri.indexOf("error")==-1&&uri.indexOf("fileDown")==-1&&uri.indexOf("fileUpload")==-1){
            return true;
        }
        return false;
    }
}
